//
//  YYCache.swift
//  YYProject
//
//  Created by 陆文宇 on 2017/8/10.
//  Copyright © 2017年 陆文宇. All rights reserved.
//

import RealmSwift

class YYCache: Object {
    @objc dynamic var key = ""
    @objc dynamic var value: Data!
    
    override class func primaryKey() -> String? {
        return "key"
    }
    
    class func set(key: String, value: Any) {
        YYRealm.async {
            let realm = YYRealm.initialize()
            
            let cache = YYCache()
            cache.key = key
            cache.value = try! JSONSerialization.data(withJSONObject: value)
            
            realm.beginWrite()
            realm.add(cache, update: true)
            try! realm.commitWrite()
        }
    }
    
    class func deleteAll() {
        let realm = YYRealm.initialize()
        let all = realm.objects(self)
        
        realm.beginWrite()
        realm.delete(all)
        try! realm.commitWrite()
    }
    
    class func getOne(key: String) -> Any? {
        let realm = YYRealm.initialize()
        let one = realm.objects(self).filter("key == '\(key)'").first
        
        if let one = one {
            return try! JSONSerialization.jsonObject(with: one.value)
        } else {
            return nil
        }
    }
}
